import 'package:jd_flutter/base/utils/jd_log.dart';
import 'package:sqflite/sqflite.dart';

import 'storage_model.dart';

///表数据操作接口
abstract class JDTableAction {
  void saveData(StorageModel model);

  void deleteData(int id);

  void update(StorageModel model);

  Future<int> getDataCount();

  Future<List<StorageModel>> getAllData();
}

///INote的的具体实现
class BaseTableAction implements JDTableAction {
  Database db;
  String tableName;
  String sqlString;

  BaseTableAction(
      {required this.db, required this.tableName, required this.sqlString}) {
    // name TEXT, value INTEGER, num REAL;
    // 需要查询的属性 可以单独写成属性
    db.execute(sqlString);
  }

  @override
  Future<List<StorageModel>> getAllData() async {
    var results = await db.rawQuery('select * from $tableName');
    var list = results.map((item) => StorageModel.fromJson(item)).toList();
    return list;
  }

  @override
  void saveData(StorageModel model) {
    db.insert(tableName, model.toJson()).then((value) {
      jdLog('insert ----${value == 0 ? 'insert失败' : 'insert成功'}');
    });
  }

  @override
  void deleteData(int id) {
    db.delete(tableName, where: 'id=$id');
  }

  @override
  Future<int> getDataCount() async {
    var result = await db.query(tableName, columns: ['COUNT(*) as cnt']);
    return result.first['cnt'] as int;
  }

  @override
  void update(StorageModel model) {
    db.update(tableName, model.toJson(),
        where: 'id =?', whereArgs: [model.id]).then((value) {
      jdLog('update ----${value == 0 ? '更新失败' : '更新成功'}');
    });
  }
}
